﻿# -*- coding:utf-8 -*-
#
# 
#
import math
from decimal import *
import datetime
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError, AppCommand, NoArgsCommand
from django.db.models.loading import get_app, get_model
from django.db import transaction
 

class Command( NoArgsCommand ):

    help = 'Import operation.'
    requires_model_validation = True
    
    @transaction.commit_manually
    def handle_noargs(self, **options):
        #from django.db.models import get_models
        # Выполнение операций в одной транзакции
        #self.process_import_operation()
        
        try:
            self.process_import_operation()
        except:
            transaction.rollback()
            print "transaction.rollback()"
        else:
            transaction.commit()    
            print "transaction.commit()"       
           

    def process_import_operation(self):
        print "Start import..."
        Operation = get_model('house', 'Operation')
        for line in open("house/import-data/import-operation.csv"):
            uline = unicode(line, "CP1251").split(';', 6)
            if len(uline) < 6:
                continue

            year = uline[0]
            month = uline[1]
            if year == '':
                continue             
            
            kind = uline[2].replace(' ','')
            name = uline[3]
            count = int(uline[4])
            price = Decimal(uline[5].replace(',','.').replace(' ',''))
            special = uline[6].replace(' ','').replace(';','').replace('\n','')
            if special == '':
                special = 'no'
            if kind == 'A': 
                amount = price * count
            else:
                amount = (price * count) * -1
            print year, month, kind, name, special
            operation = Operation(kind=kind,
                                  name=name,
                                  quantity=count,
                                  price=price,
                                  amount=amount,
                                  comment='',
                                  special_item=special,
                                  period_year = year,
                                  period_month = month,
                                  data = datetime.date(int(year), int(month), 1))
            operation.save()
             

            
            
